package com.rc.saas.tenant.controller.member;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.ExcelExportUtil;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.area.PlatformProvinceMapper;
import com.rc.saas.tenant.mapper.order.HlhtOrderInfoMapper;
import com.rc.saas.tenant.model.area.PlatformArea;
import com.rc.saas.tenant.model.area.PlatformCity;
import com.rc.saas.tenant.model.area.PlatformProvince;
import com.rc.saas.tenant.model.member.MemberAccount;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.member.RcMemberFlag;
import com.rc.saas.tenant.model.order.OrderInfo;
import com.rc.saas.tenant.model.order.OrderInfoExample;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.area.PlatformAreaService;
import com.rc.saas.tenant.service.area.PlatformCityService;
import com.rc.saas.tenant.service.member.MemberAccountService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.search.member.MemberSearch;
import com.rc.saas.tenant.service.member.RcMemberFlagService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.member.MemberInfoPrintVo;
import com.rc.saas.tenant.vo.member.MemberResultVo;
import com.rc.saas.tenant.vo.order.OrderPrintVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author frog
 * @date 2019/11/20
 */
@Controller
@RequestMapping("/member")
public class MemberController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(MemberController.class);

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private PlatformAreaService platformAreaService;

    @Autowired
    private PlatformCityService platformCityService;

    @Autowired
    private PlatformProvinceMapper platformProvinceMapper;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private RcMemberFlagService memberFlagService;


    /**
     * 跳转首页列表
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String memberInfoPage() {
        return "/templates/member/member/member";
    }

    /**
     * 返回列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listMember", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listMember(MemberSearch memberSearch) {
        PageInfo<MemberResultVo> pageInfo = memberInfoService.listPageMember(memberSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 会员角色的冻结或解冻
     */
    @ResponseBody
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public TResponse updateStatus(Long memberId) {
        try {
            memberInfoService.updateStatus(memberId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            return TResponse.FAIL("更新状态失败");
        }
    }

    /**
     * 跳转会员详情
     *
     * @return
     */
    @RequestMapping(value = "/detailMember/{memberId}", method = RequestMethod.GET)
    public String detailMember(@PathVariable("memberId") Long memberId, Model model) {
        MemberResultVo memberInfo = memberInfoService.selectMemberById(memberId);
        String provinceName = "";
        String areaName = "";
        String cityName = "";
        if (memberInfo.getProvinceId() != null) {
            PlatformProvince province = platformProvinceMapper.selectByPrimaryKey(memberInfo.getProvinceId());
            provinceName = province.getProvinceName();
        }
        if (memberInfo.getAreaId() != null) {
            PlatformArea area = platformAreaService.selectByPrimaryKey(memberInfo.getAreaId());
            areaName = area.getAreaName();
        }
        if (memberInfo.getCityId() != null) {
            PlatformCity city = platformCityService.selectByPrimaryKey(memberInfo.getCityId());
            cityName = city.getCityName();
        }

        if (StringUtils.isEmpty(memberInfo.getNickname())) {
            memberInfo.setNickname(memberInfo.getNickname2());
        }

        model.addAttribute("provinceName", provinceName);
        model.addAttribute("areaName", areaName);
        model.addAttribute("cityName", cityName);
        model.addAttribute("memberInfo", memberInfo);
        return "/templates/member/member/detailMember";
    }

    /**
     * 保存会员备注
     *
     * @return
     */
    @RequestMapping(value = "/saveMemberRemark", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveMemberRemark(Long memberId, String remark) {
        try {
            MemberInfo memberInfo = new MemberInfo();
            memberInfo.setMemberId(memberId);
            memberInfo.setRemark(remark);
            memberInfoService.updateByPrimaryKeySelective(memberInfo);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存会员备注失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 导出会员列表
     */
    @ResponseBody
    @RequestMapping("/exportMemberInfo")
    public TResponse exportMemberInfo(MemberSearch memberSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        try {
            ExportUtils.setDefaultPaging(memberSearch);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("会员列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            PageInfo<MemberResultVo> pageInfo = memberInfoService.listPageMember(memberSearch);
            EasyExcel.write(response.getOutputStream(), MemberResultVo.class).sheet("会员列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出会员列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    /**
     * 结束会员充电状态
     */
    @ResponseBody
    @RequestMapping(value = "/updateChargeStatus", method = RequestMethod.POST)
    public TResponse updateChargeStatus(Long memberId) {
        try {
            OrderInfoExample orderInfoExample = new OrderInfoExample();
            orderInfoExample.createCriteria().andStatusIn(new ArrayList<String>() {{
                add("0");
                add("1");
                add("3");
            }}).andMemberIdEqualTo(memberId);
            List<OrderInfo> orderInfos = orderInfoService.selectByExample(orderInfoExample);
            if (!CollectionUtils.isEmpty(orderInfos)) {
                return TResponse.FAIL("此账户还有正在充电中的订单，请先结束订单");
            }
            MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberId);
            memberInfo.setChargeStatus("0");
            memberInfoService.updateByPrimaryKeySelective(memberInfo);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            return TResponse.FAIL("更新状态失败");
        }
    }


    /**
     * 随机生成多个会员并返回手机号码
     */
    @ResponseBody
    @RequestMapping(value = "/registerRandomMobile", method = RequestMethod.POST)
    public TResponse registerRandomMobile(Integer memberNum) {
        if (memberNum == null || memberNum < 0) {
            memberNum = 1;
        }

        try {
            TenantUser user = ShiroUtils.getSessionUser();
            //随机生成多个会员并返回手机号码以,分割
            String memberInfo = memberInfoService.registerRandomMobile(user.getTenantCode(), memberNum);
            return TResponse.SUCCESS(memberInfo);
        } catch (Exception e) {
            return TResponse.FAIL("随机生成会员失败");
        }
    }

    /**
     * 根据手机号查找用户
     */
    @ResponseBody
    @RequestMapping(value = "/selectMemberByMobile", method = RequestMethod.GET)
    public TResponse selectMemberByMobile(String mobile){
        if (StringUtils.isBlank(mobile)){
            return TResponse.FAIL("手机号为空");
        }
        TenantUser user = ShiroUtils.getSessionUser();
        MemberInfo memberInfo = memberInfoService.selectMemberByMobile(user.getTenantCode(), mobile);
        return TResponse.SUCCESS_DATA(memberInfo);
    }

    @ResponseBody
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public TResponse deleteMember(@PathVariable("id")Long id){
        memberInfoService.deleteByPrimaryKey(id);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/updateMember", method = RequestMethod.POST)
    public TResponse updateMember(MemberInfo memberInfo){
        memberInfoService.updateByPrimaryKey(memberInfo);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/updateMemberStatus", method = RequestMethod.POST)
    public TResponse updateMemberStatus(Long id, String status) {
        try {
            MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(id);
            memberInfo.setStatus(status);
            memberInfo.setLastUpdatedTime(new Date());
            memberInfoService.updateByPrimaryKeySelective(memberInfo);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            return TResponse.FAIL("更新状态失败");
        }
    }


}
